<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Model\Member;
use DB;
use Cookie;
use Gregwar\Captcha\CaptchaBuilder;
use App\Http\Controllers\home\BaseController;

/**
 * Class MemberController 
 * @package App\Http\Controllers\home
 */
class MemberController extends BaseController
{   
    protected $table;
    protected $captcha;
    public function __construct()
    {
       $this->table =  new Member();
       $this->captcha = new CaptchaBuilder();
    }
    /**
     * 登录方法
     */
    public function login(Request $req)
    {
        $user_info = Cookie::get('user_info');
        if(empty($user_info))
        {
            if(!$_POST)
            {
                return view('home.member.login');
            }
            else
            {   
                $captcha = $req->captcha;
                $code = session('code');
                #验证码验证
                if($captcha !== $code)
                {
                    exit('验证码不正确');
                }
       
                if(!$row = Member::where('user_name',$req->user_name)->get()->first())
                {
                    exit("用户名不存在");
                }

                $salt = $row->salt;  //数据库的盐
                $password = $row->password; //数据库加密过的密码
                $password_c = $req->password; //用户提交的密码
                $password_c = md5($password_c.$salt);
                
                if( $password === $password_c )
                {   
                    Cookie::queue('last_login',$row->last_login,3600);
                    $key  = "qaJNS12KS@ASu7r5";
                    $cookiekey = md5($req->user_name.'|'.$row->user_id.'|'.$key);
                    $row->last_login = time();
                    $row->save();
                    Cookie::queue('user',$req->user_name,3600);
                    Cookie::queue('id',$row->user_id,3600);
                    Cookie::queue('user_info',$cookiekey,3600);

                    /** 分析验证是否有回调url */
                    if($url = session('backUrl')){
                        return redirect($url);
                    }
                    return redirect("/");
                }
                else
                {
                    echo '请检查您输入的密码是否正确';
                }            
            }
        }
        else
        {
            return redirect('/');
        }
    }

    /**
     * 注册方法
     */
    public function reg()
    {   
        return view('home.member.reg');
    }

    public function yzm($id)
    {
        $capth = $this->captcha->build();
        $code = $this->captcha->getPhrase();
        session(['code'=>$code]);
        $capth->output();
        header('Content-Type:image-jpeg');
    }

    public function regpost(Request $req)
    {   
        $captcha = $req->captcha;
        $code = session('code');
        #验证码验证
        if($captcha !== $code)
        {
            exit('验证码不正确');
        }


        $this -> validate($req,[
            'user_name' => 'required|max:20|min:4',
            'email' => 'required|email',
            'password' => 'required|min:6|max:16|confirmed',
        ],[
            'user_name.required'=>'请填写用户名',
            'user_name' => '用户名必须在4到20位之间',
            'user_name.max'=>'用户名不能超出20位',
            'user_name.min'=>'用户名不能少于4位',
            'email.email'=> '请填正确的邮箱',
            'email.required'=> '邮箱不能为空',
            'password.required'=>'密码不能为空',
            'password.min'=>'密码不能少于6位',
            'password.max'=>'密码不能超出16位',
            'password.confirmed'=>'两次输入的密码不一致',
        ]
        );

        
        if(Member::where('user_name',$req->user_name)->get()->first())
        {
            echo("<script>alert('用户名已存在')</script>");
            return view('home.member.reg');
        }

        if(Member::where('email',$req->email)->get()->first())
        {
            echo("<script>alert('该邮箱已存在')</script>");
            return view('home.member.reg');
        }

        $salt = $this -> salt(8);
        $password = $req -> password;
        $password = md5($password.$salt);
        $data = [
            'user_name' => $req->user_name,
            'reg_time' => time(),
            'email' => $req->email,
            'salt' => $salt,
            'password' => $password
        ];
        $res = DB::table('member')->insert($data);
        echo "<script>alert('注册成功')</script>";
        return view('home.member.login');   
    }


    protected function salt($num)
    {
        $str = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
        $str = str_shuffle($str);
        $str = substr($str, 0, $num);
        return $str;
    }

    public function logout()
    {
        $user_info = Cookie::get('user_info');
        if(!empty($user_info))
        {
            setcookie('user',null);
            setcookie('id',null);
            setcookie('user_info',null);
            return redirect("/");
        }
        else
        {
            return redirect($url);
        }
    }
    
    #个人登录页
    public function user_info()
    {   
        if(!$id = Cookie::get('id'))
        {
            return redirect('/');
        }
        else
        {
            $last_login = Cookie::get('last_login');
            $user = Member::where('user_id',$id)->get()->first();
            return view('home.member.user_info',['user'=>$user],['time'=>$last_login]);
        }
    }

    #个人信息添加
    public function info_update(Request $req)
    {   
        $id = Cookie::get('id');
        if(!$_POST)
        {    
            if(!$id)
            {
                return redirect('/');
            }
            else
            {
                $user = Member::where('user_id',$id)->get()->first();
                return view('home.member.info_update',['user'=>$user]);
            }
        }
        else
        {
            $row = Member::find($id);
            $row -> real_name = $req->real_name; 
            $row -> save();
            echo "修改成功";
        }
    }


}
